package com.hui.entity;

import com.google.gson.Gson;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: 李昭辉
 * @Date: 2021/09/26/14:27
 * @Description: 高亮结果映射
 */
public class ResultMapper implements SearchResultMapper {

    @Override
    public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
        //  用于JSON格式转换
        Gson gson = new Gson();
        // 封装结果
        List<T> list = new ArrayList<>();
        // 获取所有记录并遍历
        SearchHits hits = searchResponse.getHits();
        for (SearchHit hit : hits) {
            if (hit == null) {
                break;
            }
            // 将记录转换成map格式
            Map<String, Object> map = hit.getSourceAsMap();
            // 获取高亮数据,并遍历，将高亮字段替换到结果中
            Map<String, HighlightField> highlightFieldMap = hit.getHighlightFields();
            for (Map.Entry<String, HighlightField> entry : highlightFieldMap.entrySet()) {
                String key = entry.getKey();
                HighlightField value = entry.getValue();
                Text[] texts = value.getFragments();
                map.put(key, texts[0].toString());
            }
            // 将map转换成T格式
            T t = gson.fromJson(gson.toJson(map), aClass);
            // 将记录保存到list中
            list.add(t);
        }
        return new AggregatedPageImpl<T>(list, pageable, searchResponse.getHits().getTotalHits());
    }
}
